package com.jzr.task.job.shiyan;

import com.jzr.netty.common.base.ConnectionException;
import com.jzr.netty.common.base.SendException;
import com.jzr.netty.common.protocol.ReloadDataDeptRequest;
import com.jzr.netty.common.protocol.ReloadDataResponse;
import com.jzr.netty.common.service.AdminNettyClient;
import com.jzr.task.db1.mapper.MyPrimaryMapper;
import com.jzr.task.db1.mapper.TBedMapper;
import com.jzr.task.db1.mapper.TPatientMapper;
import com.jzr.task.db1.model.TBed;
import com.jzr.task.db1.model.TPatient;
import com.jzr.task.db2.mapper.ShiyanMapper;
import com.jzr.task.db2.model.ShiyanPatient;
import com.jzr.task.job.BaseJob;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component("Shiyan.SyncPatient")
public class ShiyanSyncPatient extends BaseJob {
    @Value("${nettyServer.ip}")
    private String nettyServerIp;

    @Value("${nettyServer.port}")
    private int nettyServerPort;

    @Autowired
    private ShiyanMapper shiyanMapper;

    @Autowired
    private MyPrimaryMapper primaryMapper;

    @Autowired
    private TPatientMapper patientMapper;

    @Autowired
    private TBedMapper bedMapper;

    @Override
    public void process() throws Exception {
        List<Integer> listExists = new ArrayList<>();
        //同步病人
        List<ShiyanPatient> list = shiyanMapper.getPatientList();
        if(list == null){return;}
        for(ShiyanPatient p : list){
            TPatient patient = new TPatient();
            BeanUtils.copyProperties(p,patient);
            patient.setUpdateTime(LocalDateTime.now());
            Integer id = primaryMapper.getPatientId(p.getCode(),p.getCureNo());
            if(id == null){
                patientMapper.insert(patient);
            }else{
                patient.setId(id);
                patientMapper.updateById(patient);
            }
            listExists.add(patient.getId());
            //检查床位
            id = primaryMapper.getBedId(p.getDeptCode(),p.getRoomCode(),p.getBedCode());
            if(id == null){
                TBed bed = new TBed();
                bed.setDeptCode(p.getDeptCode());
                bed.setRoomCode(p.getRoomCode());
                bed.setBedCode(p.getBedCode());
                bed.setPatientId(patient.getId());
                bedMapper.insert(bed);
            }else{
                TBed bed = new TBed();
                bed.setId(id);
                bed.setPatientId(patient.getId());
                bedMapper.updateById(bed);
            }
        }
        //删除不在医院的病人
        if(listExists.size()>0) {
            patientMapper.deleteBatchIds(listExists);

            //更新bed的patient_id为空（不在医院的病人)
            primaryMapper.removePatientForOutPatient(listExists);
        }

        //刷新床头卡
        List<String> depts = list.stream().map(a -> a.getDeptCode()).distinct().collect(Collectors.toList());
        if (depts != null && depts.size() > 0) {
            for (String d : depts) {
                reloadData(d, 0, null);
            }
        }
    }

    private ReloadDataResponse reloadData(String deptCode, Integer deviceType, String deviceIp) throws ConnectionException, SendException {
        ReloadDataDeptRequest request = new ReloadDataDeptRequest();
        request.setDeptCode(deptCode);
        request.setDeviceIp(deviceIp);
        request.setDeviceType(deviceType);
        try(AdminNettyClient client = new AdminNettyClient(nettyServerIp, nettyServerPort)) {
            ReloadDataResponse response = (ReloadDataResponse) client.send(request);
            return response;
        }
    }
}